package com.cloudcc.mobile.db;

import java.util.List;

import android.content.Context;

import com.cloudcc.mobile.entity.chat.DraftBox;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;

public class DraftBoxDB {
	Context context;
	DbUtils db;
	public DraftBoxDB(Context context,String dbName){
		db=DbUtils.create(context, dbName);
		this.context=context;
	}
	/**
	 * 保存数据库
	 * @param cls
	 * @throws DbException
	 */
	public  void saveDraftBox(DraftBox entity) throws DbException{
		db.save(entity);
	}
	public  void saveListDraftBox(List<DraftBox> list) throws DbException{
		db.saveAll(list);
	}

	/**
	 * 获取系统新消息数量
	 * @param <T>
	 * @throws DbException 
	 */

	public  long getNewDraftBoxNum() throws DbException{
		if(isExit()){
			long num=db.count(Selector.from(DraftBox.class).where("isNew","=","1"));
			return num;
		}else{
			return 0;
		}
	}

	/**
	 * 清空消息数量
	 * @throws DbException 
	 */

	public void clearDraftBoxNum() throws DbException{
		if(isExit()){
			List<DraftBox> list=db.findAll(Selector.from(DraftBox.class));
			for (int i = 0; i < list.size(); i++) {
				list.get(i).setIsNew("0");
			}
			db.saveOrUpdateAll(list);
		}
	}




	/**
	 * 查询所有消息
	 * @param <T>
	 */
	public <T> List<DraftBox> findAllDraftBox(Class<T> cls) throws DbException{
		@SuppressWarnings("unchecked")
		List<DraftBox> list=(List<DraftBox>) db.findAll(cls);
		return list;
	}

	/**
	 * 删除某个id的消息
	 * @param <T>
	 * @throws DbException 
	 */
	public <T> void deleteById(Class<T> cls,long id) throws DbException{
		db.deleteById(cls, id);
	}
	/**
	 * 删除所有消息
	 * @param <T>
	 * @throws DbException 
	 */
	public <T> void deleteAll(Class<T> cls) throws DbException{
		db.deleteAll(cls);
	}

	/**
	 * 判别是否存在
	 * @return
	 * @throws DbException
	 */
	public boolean isExit() throws DbException{
		boolean istable= db.tableIsExist(DraftBox.class);
		if(istable){
			long a=db.count(DraftBox.class);
			if(a>0){
				return true;
			}else{
				return false;
			}
		}
		return false;
	}
	/**
	 * 获取最后一个对象
	 * @return
	 * @throws DbException
	 */
	public  DraftBox getLastDraftBox() throws DbException{
		if(isExit()){
			List<DraftBox> list= db.findAll(DraftBox.class);
			return list.get(list.size()-1);
		}else{
			return null;
		}

	}
}
